package com.suxin.netty.remoting;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.ByteBuffer;

/**
 * @author Tang
 * @classname NettyEncoder
 * @description [ 编码器 ]
 * @date 2022/12/11 17:37
 */
@ChannelHandler.Sharable
public class NettyEncoder extends MessageToByteEncoder<RemotingCommand> {

    @Override
    protected void encode(ChannelHandlerContext ctx, RemotingCommand msg, ByteBuf out) throws Exception {
        ByteBuffer header = msg.encodeHeader();
        header.flip();
        out.writeBytes(header);
        byte[] body = msg.getBody();
        if (body != null) {
            out.writeBytes(body);
        }
    }
}
